package com.hy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.hy.base.BaseInfoProperties;
import com.hy.mapper.CandidateMapper;
import com.hy.mapper.CandidateMapperCustom;
import com.hy.pojo.Candidate;
import com.hy.pojo.bo.CandidateBO;
import com.hy.pojo.vo.CandidateVO;
import com.hy.service.CandidateService;
import com.hy.utils.PagedGridResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CandidateServiceImpl extends BaseInfoProperties implements CandidateService {

    @Autowired
    private CandidateMapper candidateMapper;
    @Autowired
    private CandidateMapperCustom candidateMapperCustom;

    /**
     * 创建或者更新候选人
     * @param candidateBO
     */
    @Override
    public void createOrUpdate(CandidateBO candidateBO) {
        Candidate candidate = new Candidate();
        BeanUtils.copyProperties(candidateBO, candidate);
        candidate.setUpdatedTime(LocalDateTime.now());

        if (StringUtils.isBlank(candidate.getId())) {
            candidate.setCreatedTime(LocalDateTime.now());
            // 插入
            candidateMapper.insert(candidate);
        } else {
            // 更新
            candidateMapper.updateById(candidate);
        }
    }

    /**
     * 获取候选人列表
     * @param realName
     * @param mobile
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PagedGridResult queryCandidateList(String realName, String mobile, Integer page, Integer pageSize) {

        // 开启分页查询，设置当前页码和每页显示条数
        PageHelper.startPage(page, pageSize);

        // 构造查询条件参数Map
        Map<String, Object> map = new HashMap<>();
        map.put("realName", realName);
        map.put("moblie", mobile);

        // 执行候选人列表查询
        List<CandidateVO> list = candidateMapperCustom.queryCandidateList(map);

        // 封装分页结果并返回
        return setterPagedGrid(list, page);

    }

    /**
     * 获取候选人详情
     * @param candidateId
     * @return
     */
    @Override
    public Candidate getDetail(String candidateId) {
        return candidateMapper.selectById(candidateId);
    }

    /**
     * 删除候选人
     * @param candidateId
     */
    @Override
    public void deleteById(String candidateId) {
        candidateMapper.deleteById(candidateId);
    }

    /**
     * 根据手机号查询候选人是否存在于数据库中
     * @param mobile
     * @return 返回符合条件的单个候选人对象，如果不存在则返回null
     */
    @Override
    public Candidate queryByMobileIsExist(String mobile) {

        // 创建查询条件
        QueryWrapper<Candidate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);

        return candidateMapper.selectOne(queryWrapper);
    }
}
